import axios from "axios";
import {getItem, getToken, removeToken} from "@/utils/auth";
import store from "@/store";
import router from "@/router";
import {getCookie} from "@/utils/Cookie";
import {Message} from "element-ui";

const api = axios.create({
    maxRedirects:5,
    timeout: 20000,

})

// 请求拦截器
api.interceptors.request.use(
    config => {
        if (store.state.token){
            config.headers['Authorization'] ='Bearer '+ store.state.token
        }else{
            config.headers['Authorization'] ='Bearer '+ getToken('token')
        }

        return config

    },
    error => {

        return Promise.reject(error)
    })

api.interceptors.response.use(response=>{
        const code = response.data.code
        switch (code){
            case 200:{
                return response.data
            }
            case 401:{
                removeToken('token')
                router.push('/login').catch(err=>{})
                return response.data
            }
            default:{
                console.log(code)
                if (window.navigator && navigator.onLine === true) {
                    Message.error(response.data.message)
                } else {
                    Message.error(response.data.message)
                }
                return Promise.reject(response.data)
            }
        }
    },
    error => {
        return Promise.reject(error)
    })

export default api
